import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import typescript from '@rollup/plugin-typescript'
import { UserConfig } from 'vitest'
import { resolve } from 'path'
import * as fs from 'fs'

const entryDir = resolve(__dirname, 'src/components/lib')
const components = fs.readdirSync(entryDir).filter((name) => {
  const componentDir = resolve(entryDir, name)
  const isDir = fs.lstatSync(componentDir).isDirectory()
  return (
    isDir &&
    name !== 'utils' &&
    fs.readdirSync(componentDir).includes('index.ts')
  )
})
const input = {}
for (const component of components) {
  input[`${component}/index`] = resolve(entryDir, component)
}

const testConfig: UserConfig = {
  globals: true,
  environment: 'jsdom',
  transformMode: {
    web: [/.[tj]sx$/]
  }
}

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    port: 4000
  },
  plugins: [
    vue({
      template: {
        compilerOptions: {}
      }
    }),
    vueJsx({
      mergeProps: false
    }),
    typescript({
      tslib: require.resolve('typescript'),
      rootDir: entryDir
    })
  ],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  },
  build: {
    lib: {
      entry: resolve(entryDir, 'index.ts'),
      fileName: 'index',
      formats: ['es']
    },
    rollupOptions: {
      external: ['vue', 'ant-design-vue', '@surely-vue/table'],
      input: {
        index: resolve(entryDir, 'index.ts'),
        ...input
      },
      output: {
        format: 'es',
        globals: {
          vue: 'Vue',
          'ant-design-vue': 'antDesignVue'
        },
        entryFileNames: '[name].js'
      },
      plugins: []
    }
  },
  // @ts-ignore
  test: testConfig
})
